package cn.you.GenghisKhan.config;

import cn.you.GenghisKhan.common.utils.PropertyUtil;
import cn.you.GenghisKhan.config.bean.AppBean;
import cn.you.GenghisKhan.db.relation.bean.DatabaseBean;
import cn.you.GenghisKhan.db.relation.bean.TenantBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

public abstract class AbstractConfigCentre implements ConfigCentre{
    private static final Logger logger = LoggerFactory.getLogger(AbstractConfigCentre.class);

    private static List<TenantBean> TENANTBEAN;
    private static final Map<String, DatabaseBean> DATABASES = new ConcurrentHashMap<String, DatabaseBean>();
    private static Map<String,AppBean> APPBEANS=new ConcurrentHashMap<String, AppBean>();
    abstract List<TenantBean> createTenantBeans();
    abstract DatabaseBean createDatabaseBean(String tag);
    abstract Map<String, DatabaseBean> createDatabaseBeanMap();
    abstract AppBean createAppBean(String appName);
    @Override
    public List<TenantBean> getTenantBeans () {
        if(TENANTBEAN==null)
        {
            TENANTBEAN=createTenantBeans();
        }
        return TENANTBEAN;
    }

    @Override
    public AppBean getAppBean(String appName) {
        if(appName==null)
            logger.error("配置中心读取DatabaseBean异常：appName参数为空");
        AppBean appBean = APPBEANS.get(appName);
        if (appBean != null) {
            return appBean;
        }
        appBean=createAppBean(appName);
        APPBEANS.put(appName,appBean);
        return appBean;
    }

    @Override
    public AppBean getAppBean() {
        String appName= PropertyUtil.getProperty("app.name");
        if(appName==null)
            logger.error("配置中心读取AppBean异常：app.name没有设置");
        AppBean appBean = APPBEANS.get(appName);
        if (appBean != null) {
            return appBean;
        }
        appBean=createAppBean(appName);
        APPBEANS.put(appName,appBean);
        return appBean;
    }
    @Override
    public DatabaseBean getDatabaseBean (String tag) {
        if(tag==null)
            logger.error("配置中心读取DatabaseBean异常：数据库别名参数为空");
        if(DATABASES.size()==0)
        {
            Map<String, DatabaseBean> getDataBaseBeanMap=createDatabaseBeanMap();
            if(getDataBaseBeanMap!=null&&getDataBaseBeanMap.size()>0)
            {
                Set<Map.Entry<String,DatabaseBean>> entrySet=getDataBaseBeanMap.entrySet();
                for(Map.Entry<String, DatabaseBean> entry:entrySet){
                    String key=entry.getKey();
                    DatabaseBean databaseBean=entry.getValue();
                    DATABASES.put(key, databaseBean);
                }
            }
        }
        DatabaseBean databaseBean = DATABASES.get(tag);
        if (databaseBean != null) {
            return databaseBean;
        }
        databaseBean=createDatabaseBean(tag);

        return databaseBean;
    }
}
